package net.wicp.tams.common.callback.impl.valueencoder;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.callback.IValueEncoder;

@SuppressWarnings("rawtypes")
public class ValueEncoderMap implements IValueEncoder<Map> {

	@Override
	public String toClient(Map value) {
		String str = value.toString();
		return str;
	}

	/***
	 * 把map.toString()转成的string返转为map，现只支持简单的转换，eg:{topic=test-topic2}
	 */
	@Override
	public Map toValue(String clientValue) {
		if (StringUtil.isNull(clientValue)) {
			return new HashMap<>();
		}
		Map retmap = null;
		try {
			retmap = JSONObject.parseObject(clientValue, Map.class);// 偿试用json处理
		} catch (Throwable e) {// 用map.toString()处理
			String jsonstr = clientValue.replace(" ", "").replace("=", "\":\"").replace(",", "\",\"")
					.replace("{", "{\"").replace("}", "\"}");
			retmap = JSONObject.parseObject(jsonstr, Map.class);
		}

		return retmap;
	}

}
